package com.example.demo.Controller;

import com.example.demo.Entity.Book;
import com.example.demo.Entity.ReturnBook;
import com.example.demo.Service.BookService;
import com.example.demo.Vo.Response;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.*;

@RestController
@CrossOrigin
public class BookController<resultList> {
    @Autowired
    private BookService bookService;

    @PostMapping("/api/visiter/book_list_by_category")
    public Response bookListByCategory(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        Map<String, ArrayList<ReturnBook>> map = new HashMap<>();
        String category = reMap.get("categoryName");
        try {
            ArrayList<Book> bookArrayList = bookService.selectBookByCategory(category);
            ArrayList<ReturnBook> returnBookArrayList = new ArrayList<>();
            for(Book tem : bookArrayList){
                ReturnBook returnBook = ReturnBook.trans(tem);
                returnBookArrayList.add(returnBook);
            }
            map.put("bookList", returnBookArrayList);
            response = Response.createBySuccess("成功查询图书列表", map);
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/visiter/book_list_by_keyword")
    public Response bookListByKeyWord(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        Map<String, ArrayList<ReturnBook>> map = new HashMap<>();
        String keyword = reMap.get("keyWord");
        try {
            ArrayList<Book> bookArrayList = bookService.selectBookByKeyWord(keyword);
            ArrayList<ReturnBook> returnBookArrayList = new ArrayList<>();
            for(Book tem : bookArrayList){
                ReturnBook returnBook = ReturnBook.trans(tem);
                returnBookArrayList.add(returnBook);
            }
            map.put("bookList", returnBookArrayList);
            response = Response.createBySuccess("成功查询图书列表",map);
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @GetMapping("/api/visiter/bookdetailed/{ISBN}")
    public Response bookDetailed(HttpServletRequest request, @PathVariable("ISBN") String ISBN){
        Response response = null;
        Map<String, ArrayList<Object>> map = new HashMap<>();
        String isbn = ISBN;
        try{
            Book book = bookService.selectBookByISBN(isbn);
            ReturnBook returnBook = ReturnBook.trans(book);
            String categoryName = bookService.selectCategoryName(returnBook.getCategoryId());
            System.out.println(categoryName);
            ArrayList<Object> bookAndCategoryName = new ArrayList<>();
            bookAndCategoryName.add(returnBook);
            bookAndCategoryName.add(categoryName);
            map.put("bookISBN",bookAndCategoryName);
            response = Response.createBySuccess("查看图书详细信息",map);
        }catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    // 四个跟管理员有关的图书操作: 查看所有图书信息 插入新图书 删除图书 修改图书信息
    @GetMapping("/api/visiter/book/all_information")
    public Response viewAllBookInformation(HttpServletRequest request) {
        Response response = null;
        Map<String, List<ReturnBook>> map = new HashMap<>();
        try {
            List<Book> bookList = bookService.selectAll();
            if (bookList.isEmpty()) {
                response = Response.createBySuccessMessage("图书列表空空如也");
            } else {
                ArrayList<ReturnBook> returnBookArrayList = new ArrayList<>();
                for(Book tem : bookList){
                    ReturnBook returnBook = ReturnBook.trans(tem);
                    returnBookArrayList.add(returnBook);
                }
                map.put("bookList", returnBookArrayList);
                response = Response.createBySuccess("以下为所有图书信息", map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }


    @PostMapping("/api/admin/book/create_a_new_book") //新建图书
    public Response createNewBook(HttpServletRequest request, @RequestBody Map<String, Object> reMap) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Response response = null;
        Book book = new Book();
        String ISBN = (String) reMap.get("isbn");
        String Title = (String) reMap.get("title");
        String Author = (String) reMap.get("author");
        String CategoryId = (String) reMap.get("categoryId");
        String Pages = (String) reMap.get("pages");
        String Words = (String) reMap.get("words");
        String Publisher = (String) reMap.get("publisher");
        String tem = (String) reMap.get("price");
        float Price = Float.parseFloat(tem);
        String TotalCount = (String) reMap.get("totalCount");
    //    String pictureUrl =(String) reMap.get("pictureUrl");
        String getDate = (String) reMap.get("actionDate");
        String introduction = (String) reMap.get("introduction");
        String PictureBase = (String) reMap.get("pictureBase");
        Date actionDate = null;
        try {
            actionDate = sdf.parse(getDate);
        } catch (ParseException e) {
            e.printStackTrace();
            response = Response.createByErrorMessage("日期输入形式错误");
            return response;
        }

        class checkIsNull {
            public boolean check(String... arc){
                for(String tem : arc){
                    if(tem.isEmpty()) {
                        return false;
                    }
                }
                return true;
            }
        }
        try {
            checkIsNull entity = new checkIsNull();
            if(entity.check(ISBN, Title, Author, Publisher) == false){
                response = Response.createByErrorMessage("未设置必要的初始信息");
            }
            else if(CategoryId == null || Integer.parseInt(CategoryId) == 0 || Price == 0){
                response = Response.createByErrorMessage("未设置必要的初始信息");
            }
            else{
                Book checkExist = bookService.selectBookByISBN(ISBN);
                if(checkExist != null) {
                    response = Response.createByErrorMessage("ISBN号重复，请重新设置");
                }
                else {
                    book.setISBN(ISBN);
                    book.setTitle(Title);
                    book.setAuthor(Author);
                    book.setCategoryId(Integer.parseInt(CategoryId));
                    book.setPages(Integer.parseInt(Pages));
                    book.setWords(Integer.parseInt(Words));
                    book.setPublisher(Publisher);
                    book.setPrice(Price);
                    book.setTotalCount(Integer.parseInt(TotalCount));
                    book.setIntroduction(introduction);
                    book.setActionDate(actionDate);
                //    book.setPictureUrl(pictureUrl);
                    book.setPictureBase(PictureBase);
                    bookService.createNewBook(book);
                    response = Response.createBySuccessMessage("成功创建图书");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/admin/book/delete_book")
    public Response deleteBook(HttpServletRequest request, @RequestBody Map<String, Object> reMap) {
        Response response = null;
        String isbn = (String) reMap.get("isbn");
        try {
            if(bookService.deleteBook(isbn) == false){
                response = Response.createByErrorMessage("没有对应编号图书");
            }
            else{
                response = Response.createBySuccessMessage("成功删除ISBN为"+isbn +"的图书");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/admin/book/edit_book")
    public Response editBook(HttpServletRequest request, @RequestBody Map<String, Object> reMap) {
        Response response = null;
        String ISBN = (String) reMap.get("isbn");
        try{
            String Title = (String) reMap.get("title");
            String Author = (String) reMap.get("author");
            String CategoryId = (String) reMap.get("categoryId");
            String Pages = (String) reMap.get("pages");
            String Words = (String) reMap.get("words");
            String Publisher = (String) reMap.get("publisher");
            String Price = (String) reMap.get("price");
            String TotalCount = (String) reMap.get("totalCount");
            String Introduction = (String) reMap.get("introduction");
            String ActionDate = (String) reMap.get("actionDate");
        //    String Picture = (String) reMap.get("pictureUrl");
            String PictureBase = (String) reMap.get("pictureBase");
            bookService.editBookTitle(ISBN, Title);
            bookService.editBookAuthor(ISBN, Author);
            bookService.editBookPublisher(ISBN, Publisher);
            bookService.editBookIntroduction(ISBN, Introduction);
            bookService.editBookPictureBase(ISBN, PictureBase);
        //    bookService.editBookPictureUrl(ISBN, Picture);
        //    if(Picture.isEmpty() == false){
        //        bookService.editBookPictureBase(ISBN, PictureBase);
        //    }
            if(bookService.editBookCategoryID(ISBN, CategoryId) == false){
                response = Response.createByErrorMessage("输入分类号格式错误");
                return response;
            }
            if(bookService.editBookPages(ISBN, Pages) == false){
                response = Response.createByErrorMessage("输入页数形式或范围错误");
                return response;
            }
            if(bookService.editBookWords(ISBN, Words) == false){
                response = Response.createByErrorMessage("输入字数形式或范围错误");
                return response;
            }

            if(bookService.editBookPrice(ISBN, Price) == false){
                response = Response.createByErrorMessage("输入价格形式或范围错误");
                return response;
            }
            if(bookService.editBookTotalCount(ISBN, TotalCount) == false){
                response = Response.createByErrorMessage("输入数量形式或范围错误");
                return response;
            }
            if(bookService.editBookActionDate(ISBN, ActionDate) == false){
                response = Response.createByErrorMessage("输入发行日期形式或格式错误");
                return response;
            }
            response = Response.createBySuccessMessage("成功修改图书信息");
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }
}
